<html>

<head>
    <title>测试swoole通信</title>
    <style>
        #show {
            border: 1px solid gold;
            height: 50%;
            overflow: auto;
        }
    </style>
</head>

<body>
    <div id="show">

    </div>

    <!--<form action="" onsubmit="send()">-->
    <input type="text" id='output' onblur="send()" onkeydown="clickSend()">
    <!--</form>-->

    <script>
        var wsServer = 'ws://118.24.26.76:9502/ws';
        var ws = new WebSocket(wsServer);
        ws.onopen = function (evt) {
            console.log("Connected to WebSocket server.");
        };

        ws.onclose = function (evt) {
            console.log("Disconnected");
        };

        ws.onmessage = function (evt) {
            data = JSON.parse(evt.data);
            switch (data.type) {
                case 'ping':
                    ws.send('{"type":"pong"}');
                    break;
                default:
                    var show = document.getElementById('show')
                    show.innerHTML = show.innerHTML + "<br>" + data.data
                    show.scrollTop = show.scrollHeight;
                    break;

            }
            // console.log('Retrieved data from server: ' + evt.data);
        };

        ws.onerror = function (evt, e) {
            console.log('Error occured: ' + evt.data);
        };

        window.onload = function () {
            var input = document.getElementById('output')
            input.focus()
        }

        function send() {
            var input = document.getElementById('output')
            console.log(input.value)
            // ws.send(input.value)
        }

        function clickSend() {
            // 兼容FF和IE和Opera
            var theEvent = window.event;
            var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
            if (code == 13) {
                var input = document.getElementById('output')
                ws.send('{"type":"text","data":"' + input.value + '"}');
                var show = document.getElementById('show')
                show.innerHTML = show.innerHTML + "<br>自己：" + input.value
                show.scrollTop = show.scrollHeight;
                input.value = ''
            }
        }
    </script>
</body>

</html>